class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
        this.hasFilterValue = true;
    }
    GetFilterValue() {
        let item = {};

        item['CustomerId'] = parseInt(this.dataId);
        item['CurrentUserId'] = parseInt($("#UserId").val());
        item['WorkFlowId'] = $("#WorkFlowId").val() === '' ? 0 : parseInt($("#WorkFlowId").val());
        item['Limit'] = parseInt($("#page-size_02").val());
        item['PageIndex'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));

        return item;
    }
    // 得到数据
    GetEntityData() {
        var item = {};
        item['customerId'] = $("#CustomerId").val();
        item['customerNo'] = $.trim($("#CustomerNo").val());
        item['customerName'] = $.trim($("#CustomerName").val());
        item['shortName'] = parent.formatNullInputValue($.trim($("#ShortName").val()));
        item['country'] = parent.formatNullInputValue($.trim($("#Country").val()));
        item['province'] = parent.formatNullInputValue($.trim($("#Province").val()));
        item['attn'] = parent.formatNullInputValue($.trim($("#Attn").val()));
        item['attnJob'] = parent.formatNullInputValue($.trim($("#AttnJob").val()));
        item['attnTel'] = parent.formatNullInputValue($.trim($("#AttnTel").val()));
        item['attnMobil'] = parent.formatNullInputValue($.trim($("#AttnMobil").val()));
        item['fax'] = parent.formatNullInputValue($.trim($("#Fax").val()));
        item['email'] = parent.formatNullInputValue($.trim($("#Email").val()));
        item['openAccountBank'] = parent.formatNullInputValue($.trim($("#OpenAccountBank").val()));
        item['bankAccount'] = parent.formatNullInputValue($.trim($("#BankAccount").val()));
        item['address'] = parent.formatNullInputValue($.trim($("#Address").val()));
        item['taxRateId'] = parent.formatNullInputValue($.trim($("#TaxRateId").val()));
        item['settlementModeId'] = parent.formatNullInputValue($.trim($("#SettlementModeId").val()));
        item['freightForwarding'] = parent.formatNullInputValue($.trim($("#FreightForwarding").val()));
        item['dstinationPort'] = parent.formatNullInputValue($.trim($("#DstinationPort").val()));
        item['description'] = parent.formatNullInputValue($.trim($("#Description").val()));
        item['catalogueId'] = $.trim($("#CatalogueId").val());
        item['createdBy'] = $("#UserId").val();
        item['updatedBy'] = $("#UserId").val();

        return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.CustomerEntity;
        $("#CustomerId").val(item.customerId);
        $("#CustomerNo").val(item.customerNo);
        $("#CustomerName").val(item.customerName);
        $("#ShortName").val(item.shortName);
        $("#Country").val(item.country);
        $("#Province").val(item.province);
        $("#Attn").val(item.attn);
        $("#AttnJob").val(item.attnJob);
        $("#AttnTel").val(item.attnTel);
        $("#AttnMobil").val(item.attnMobil);
        $("#Fax").val(item.fax);
        $("#Email").val(item.email);
        $("#OpenAccountBank").val(item.openAccountBank);
        $("#BankAccount").val(item.bankAccount);
        $("#Address").val(item.address);
        $("#TaxId").val(item.taxId);
        $("#TaxRateId").val(item.taxRateId);
        $("#TaxRateName").val(item.taxRateName);
        $("#SettlementModeId").val(item.settlementModeId);
        $("#SettlementModeName").val(item.settlementModeName);
        $("#CatalogueId").val(item.catalogueId);
        $("#CatalogueName").val(item.catalogueName);
        $("#Description").val(item.description);
        $("#FreightForwarding").val(item.freightForwarding);   // 货代客户
        $("#DstinationPort").val(item.dstinationPort);         // 到货港口
        $("#NodeText").val(item.catalogueName);

        // 最后的审核人、审核日期
        //$("#CheckedBy").val(item.checkedBy);
        //$("#CheckedByName").val(item.checkedByName);
        //$("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
        //$("#CheckedStatus").val(item.checkedStatus);
        //$('#FlowOrderNo').val(item.flowOrderNo);
        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;

        _InstancePageSizeLable.BuildDataTable(data.SizeLableData);

        this.SetPageElementStatus();
        $("#CustomerNo").focus();
    }
    SetPageElementStatus() {
        super.SetPageElementStatus(function () {
            //$("#ButSave").hide();
        }, function () {
            //$("#ButSave").show();
        }, function () {

        });
    }
    Save(flag) {
        super.Save(function (data, $self) {
            if (data > 0) {
                if (parseInt($self.pageStatus) === 1) {
                    $("#CustomerId").val(data);   // 设置刚才插入的记录ID
                    $self.dataId = data;
                    $self.pageStatus = 2;
                }
                if (flag === 0) {
                    $self.New();
                }
            }
        });
    }
    OnNew() {
        // 默认设置一些值
        $('#CustomerId').val("0");
        super.OnNew();
        // 初始化所属材料分类
        $('#CatalogueId').val($("#NodeId").val());
        $('#CatalogueName').val($("#NodeText").val());
        $("#CustomerNo").focus();
    }
    DoChoiceTaxRate() {
        let _choice = new CommonChoice();
        _choice.DoChoiceTaxRate(0, (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#TaxRateName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#TaxRateId").val(data[0]);
                $("#TaxRateName").val(data[2]);
            }
        });
    }
    DoChoiceSettlementMode() {
        let _choice = new CommonChoice();
        _choice.DoChoiceSettlementMode(0, (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#SettlementModeName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#SettlementModeId").val(data[0]);
                $("#SettlementModeName").val(data[1]);
            }
        });
    }
    DoChoiceCatalogue() {
        let _choice = new CommonChoice();
        _choice.DoChoiceCatalogue('/master/customer/catalogue/choice.html', '选择所属客户目录', (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#CatalogueName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#CatalogueId").val(data[0]);
                $("#CatalogueName").val(data[1]);
                $("#CatalogueName").focus();
            }
        });
    }
}

class MyPageSizeLabel extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.selectedItemList = [];
        this.orderby = "";
    }
    SetPageSize() {
        $.cookie("customer_size_lable_pagesize", $("#page-size_02").val());
        this.FetchForPage(1);
    }
    // 获取明细表分页信息
    GetFilterValue(pageIndex) {
        if (pageIndex !== 0) {
            $("#page_indicator_block_02").attr("_msh_page", pageIndex);
        }

        let item = {};
        item['CustomerId'] = parseInt($.trim($("#CustomerId").val()));
        item['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者
        item['Limit'] = parseInt($("#page-size_02").val());        // limit;
        item['PageIndex'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));
        item['OrderBy'] = this.orderby;

        return JSON.stringify(item);
    }
    // 取得分页数据
    FetchForPage(pageIndex) {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/master/customer/size_lable/fetchForPage.html",
            timeout: 60 * 1000,
            data: this.GetFilterValue(pageIndex),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                $("#loading__indicator_02 i").addClass("fa-spin");
                $("#loading__indicator_02").show();
            }
        }).done((data) => {
            this.BuildDataTable(data);
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(() => {
            $("#loading__indicator_02 i").removeClass("fa-spin");
            $("#loading__indicator_02").hide();
        });
    }
    BuildDataTable(result) {
        $("#page_indicator_block_02").attr("_msh_page", 1);
        $("#page_indicator_block_02").text("1 of 1");
        $('#tabData04 tbody').empty();
        if (result.Success === false) {
            this.rows = 0;
            $("#check_all_for_size").prop("checked", false);
            this.selectedItemList = [];
            // 自适应高度
            _InstancePageSizeLable.AutoAdjustTableHeightForLines();
            return false;
        }
        // 设置翻页控件
        if (result.TotalPages > 0) {  //总页数
            $("#wrapper__navbar_02").data("swPagination").options.max_page = result.TotalPages;
        } else {
            $("#wrapper__navbar_02").data("swPagination").options.max_page = 1;
        }
        if (result.PageIndex > 0) { //当前页数
            $("#wrapper__navbar_02").data("swPagination").options.current_page = result.PageIndex;
            $("#wrapper__navbar_02").data("swPagination").setPage(result.PageIndex);
        } else {
            $("#wrapper__navbar_02").data("swPagination").options.current_page = 1; //当前页数
            $("#wrapper__navbar_02").data("swPagination").setPage(1);
        }
        let currentPage = result.PageIndex;
        // 得到数据列表
        result = result.DataList;
        if (result === null) {
            this.rows = 0;
            // 自适应高度
            _InstancePageSizeLable.AutoAdjustTableHeightForLines();
            return false;
        }
        let content = '';
        this.rows = result.length;
        this.numCheckbox = result.length;
        for (let i = 0; i < result.length; i++) {
            //let sequence = i + 1 + (currentPage - 1) * parseInt($("#page-size_02").val());
            content += '<tr _mash_id="' + result[i].sizeId + '">';
            content += '<td class="cell_choice"><label class="btn" for="R-' + result[i].sizeId + '"><input id="R-' + result[i].sizeId + '" name="_check_row" type="checkbox" onclick="_InstancePageSizeLable.DoCheckRow($(this), \'_check_row\', $(\'#check_all_for_size\'));" value="' + result[i].sizeId + '"/><i></i><span></span></label></td>';
            //content += '<td style="text-align:center;">' + sequence + '</td>';
            content += '<td class="column__action"><span title="删除" class="trash act__delete" onclick="_InstancePageSizeLable.DeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            content += '<td>' + formatNullData(result[i].sizeName) + '</td>';
            content += '<td class="edited-cell">' + formatNullData(result[i].sizeLable) + '</td>';
            content += '<td class="edited-cell">' + formatNullData(result[i].description) + '</td>';
            content += '</tr>';

            $('#tabData04 tbody').append(content);
            content = '';
        }
        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();

        let _cellid = "_cell__field";
        let _cellname = "__cell__field";
        $('#tabData04 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), _cellid, _cellname, 0);
        });

        setOneTableRowColor("tabData04");
        this.ResetSelectRowStatus();
    }
    ImportFromSize($obj) {
        let params = {};
        params['CustomerId'] = parseInt($("#CustomerId").val());
        params['DeletedBy'] = parseInt($.trim($("#UserId").val()));
        params['Limit02'] = parseInt($("#page-size_02").val());
        params['PageIndex02'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));
        params['OrderBy'] = this.orderby;

        super.DoAjax(params, "/master/customer/size_lable/import.html", (data, _this) => {
            if (data.Success === true) {
                _this.BuildDataTable(data.SizeLableData);
                ShowSuccessMessagePanel("引入尺码数据成功。");
            }
        }, $obj);
    }
    // 拷贝其他客户尺码标号数据
    CopyFromOther($obj) {
        let _choice = new CommonChoice();
        let params = {};
        params['Flag'] = 0;
        params['CurrentUserId'] = null;
        params['NotInGroupId'] = null;
        _choice.DoChoiceCustomer(params, "选择客户", (data) => {
            if (data) {
                params = {};
                params['CustomerId'] = parseInt($("#CustomerId").val());
                params['OtherCustomerId'] = parseInt(data[0]);
                params['UpdatedBy'] = parseInt($.trim($("#UserId").val()));
                params['Limit02'] = parseInt($("#page-size_02").val());
                params['PageIndex02'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));
                params['OrderBy'] = this.orderby;

                super.DoAjax(params, "/master/customer/size_lable/copy.html", (data, _this) => {
                    if (data.Success === true) {
                        _this.BuildDataTable(data.SizeLableData);
                        ShowSuccessMessagePanel("拷贝数据成功。");
                    }
                }, $obj);
            }
        });
    }
    GetLinesData() {
        let _result = {};
        let itemList = [];
        $('#tabData04 tbody').find("tr").each(function () {
            if ($(this).find('td.dirty').length > 0) {
                let item = {};
                item['customerId'] = $("#CustomerId").val();
                item['sizeId'] = $(this).attr('_mash_id');
                item['sizeLable'] = $.trim($(this).find('td').eq(3).text());
                item['description'] = formatNullInputValue($.trim($(this).find('td').eq(4).text()));
                item['updatedBy'] = $("#UserId").val();
                itemList.push(item);
            }
        });

        _result['UpdateList'] = itemList;
        _result['CustomerId'] = parseInt($("#CustomerId").val());
        _result['Limit02'] = parseInt($("#page-size_02").val());
        _result['PageIndex02'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));
        _result['OrderBy'] = this.orderby;

        return JSON.stringify(_result);
    }
    SaveLines($obj) {
        //step 1、进行页面验证，失败则返回
        //let _success = CheckGridInput02();
        //if (!_success)
        //    return;

        super.SaveLines("/master/customer/size_lable/update.html", (data, _this) => {
            if (data.Success === true) {
                // 刷新合同明细
                _this.BuildDataTable(data.SizeLableData);
                ShowSuccessMessagePanel("保存成功。");
            }
        }, $obj);
    }
    DeleteLines($self) {
        let params = {};
        params['CustomerId'] = parseInt($("#CustomerId").val());
        params['SizeId'] = $self.parent().parent().attr("_mash_id");
        params['DeletedBy'] = parseInt($.trim($("#UserId").val()));
        params['Limit02'] = parseInt($("#page-size_02").val());
        params['PageIndex02'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));
        params['OrderBy'] = this.orderby;

        super.DeleteLines(params, "/master/customer/size_lable/delete.html", (data, _this) => {
            if (data.Success === true) {
                _this.BuildDataTable(data.SizeLableData);
                ShowSuccessMessagePanel("删除成功。");
            }
        }, $self);
    }
    GetCheckedLinesData() {
        let _result = {};
        let _itemList = [];
        if (Object.keys(this.selectedItemList).length > 0) {
            for (let key in this.selectedItemList) {
                let item = {};
                item['customerId'] = $("#CustomerId").val();
                item['sizeId'] = this.selectedItemList[key].SizeId;
                item['updatedBy'] = $.trim($("#UserId").val());

                _itemList.push(item);
            }
        }

        _result['ItemList'] = _itemList;
        _result['CustomerId'] = $("#CustomerId").val();
        _result['DeletedBy'] = $.trim($("#UserId").val());
        _result['Limit02'] = parseInt($("#page-size_02").val());
        _result['PageIndex02'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));
        _result['OrderBy'] = this.orderby;

        return JSON.stringify(_result);
    }
    BatchDeleteLines($obj) {
        if (Object.keys(this.selectedItemList).length === 0) {
            ShowErrorMessagePanel("请选择批量删除的记录。");
            return false;
        }
        super.BatchDeleteLines('/master/customer/size_lable/batch_delete.html', (data, _this) => {
            if (data.Success === true) {
                $("#check_all_for_size").prop("checked", false);
                this.selectedItemList = [];
                // 刷新合同明细
                _this.BuildDataTable(data.SizeLableData);
                ShowSuccessMessagePanel("删除成功。");
            }
        }, $obj);
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        let key = $self.val();
        let $row = $self.parent().parent().parent();

        if ($self.is(":checked") === true) {
            $row.addClass("row__selected");
            // 设置 编辑、删除按钮失效
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", "");
            let item = {};
            // 为翻页选择做准备
            item["SizeId"] = key;
            this.selectedItemList[key] = item;
        } else {
            $row.removeClass("row__selected");
            // 设置删除按钮有效
            let _event_delete_onclick = "_InstancePageSizeLable.DeleteLines($(this))";
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", _event_delete_onclick);
            delete this.selectedItemList[key];
        }
    }
    // 每次翻页都恢复选定结果
    ResetSelectRowStatus() {
        let _this = this;
        $("#tabData04 tbody").find("tr").each(function (index) {
            let key = $(this).attr("_mash_id");
            if (_this.selectedItemList[key] !== undefined) {
                $(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row']").eq(0).prop('checked', true);
                $(this).addClass("row__selected");
                // 设置删除按钮失效
                //$(this).children('td').eq(2).children('span').eq(0).attr("onclick", "");
            }
        });
        // 设置选择全部的状态
        let n = $("input[type='checkbox'][name='_check_row']:checked").length;
        if (n < $("#tabData04 tbody").find("tr").length || n === 0) {
            $("#check_all_for_size").prop("checked", false);
        } else {
            $("#check_all_for_size").prop("checked", true);
        }
    }
    SortTable(order_by) {
        this.orderby = order_by;
        this.FetchForPage(1);
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = $("#divD4").offset().top;
        let _rc = Math.floor((h - _tabTop - 70) / 25);
        let _dh = _rc * 25;
        let _tah = this.rows * 25;
        _dh = (_tah >= _dh) ? _dh : _tah;

        $("#divD4").css({"max-height": _dh, height: _dh});
    }
}

var _InstancePageHeader = null;
var _InstancePageSizeLable = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = $("#Action").val();
    let _dataId = $("#CustomerId").val();

    let customer_list_result = $.cookie("customer_list_result") === undefined ? "" : $.cookie("customer_list_result");
    let _pageListData = [];
    if (customer_list_result !== "") {
        _pageListData = customer_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }

    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/master/customer/list.html",
            "/master/customer/fetchByKey.html",
            "/master/customer/save.html",
            "/master/customer/export.html",
            "/master/customer/print.html");
    _InstancePageSizeLable = new MyPageSizeLabel();

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelContent"});

    // 设置分页控制 （操作区域）
    $("#wrapper__navbar_02").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("#page_indicator_block_02").attr("_msh_page", page);
            _InstancePageSizeLable.FetchForPage(page);
        }
    });
    $("#loading__indicator_02").hide();

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    var w = $(window).width();
    var h = $(window).height();

    $(".data__table_wrapper").css({width: w - 40});
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
    return arg !== value;
}, "Value must not equal arg.");

$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _CustomerNo: "required",
            _CustomerName: "required",
            _ShortName: "required",
            _Fax: "required",
            _TaxRateName: "required",
            _SettlementModeName: "required"
        },
        messages: {
            _CustomerNo: "请填写客户编号。",
            _CustomerName: "请填写客户名称。",
            _ShortName: "请填写客户简称。",
            _Fax: "请填写传真。",
            _TaxRateName: "请填写税率。",
            _SettlementModeName: "请填写结算方式。"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});